﻿#pragma once
#include "MdbStructs.h"
#include "MdbPrimaryKeys.h"
#include "MdbUniqueKeys.h"
#include "MdbIndexes.h"
#include "MemCacheTemplate.h"
#include "MdbSubscriber.h"
#include <shared_mutex>
#include <atomic>


namespace mdb
{
	class Mdb;
	class TickTable
	{
	public:
		TickTable(Mdb* mdb);
		~TickTable();
		void Subscribe(MdbSubscriber* mdbSubscriber);
		void UnSubscribe();
		void LockShared();
		void UnlockShared();
		void InitDB();
		bool Insert(Tick* record);
		void Erase(Tick* record);
		int EraseByInstrumentIDIndex(const InstrumentIDType& InstrumentID);
		bool Update(Tick* const oldRecord, Tick* const newRecord, bool updateDB = true);
		void TruncateTable();
		void Dump(const char* dir);

	private:
		void EraseUniqueKey(Tick* record);
		void EraseIndex(Tick* record);

	public:
		std::atomic<bool> m_DBInited;
		Mdb* m_Mdb;
		MdbSubscriber* m_MdbSubscriber;
		std::shared_mutex m_SharedMutex;
		TickPrimaryKey* m_PrimaryKey;
		TickIndexInstrumentID* m_InstrumentIDIndex;
	};

	class BarTable
	{
	public:
		BarTable(Mdb* mdb);
		~BarTable();
		void Subscribe(MdbSubscriber* mdbSubscriber);
		void UnSubscribe();
		void LockShared();
		void UnlockShared();
		void InitDB();
		bool Insert(Bar* record);
		void Erase(Bar* record);
		int EraseByInstrumentIDIndex(const Int64Type& TradingDay, const ExchangeIDType& ExchangeID, const InstrumentIDType& InstrumentID);
		int EraseByTradingDayIndex(const Int64Type& TradingDay);
		bool Update(Bar* const oldRecord, Bar* const newRecord, bool updateDB = true);
		void TruncateTable();
		void Dump(const char* dir);

	private:
		void EraseUniqueKey(Bar* record);
		void EraseIndex(Bar* record);

	public:
		std::atomic<bool> m_DBInited;
		Mdb* m_Mdb;
		MdbSubscriber* m_MdbSubscriber;
		std::shared_mutex m_SharedMutex;
		BarPrimaryKey* m_PrimaryKey;
		BarIndexInstrumentID* m_InstrumentIDIndex;
		BarIndexTradingDay* m_TradingDayIndex;
	};

}
